
import network
from math import atan,tan,degrees,pi,acos
from machine import PWM,Pin
import time
import math

class Servo:
    def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
        self.min_us = min_us
        self.max_us = max_us
        self.us = 0
        self.freq = freq
        self.angle = angle
        self.pwm = PWM(pin, freq=freq, duty=0)

    def write_us(self, us):
        if us == 0:
            self.pwm.duty(0)
            return
        us = min(self.max_us, max(self.min_us, us))
        duty = us * 1024 * self.freq // 1000000
        self.pwm.duty(duty)

    def write_angle(self, degrees=None, radians=None):
        if degrees is None:
            degrees = math.degrees(radians)
        degrees = degrees % 360
        total_range = self.max_us - self.min_us
        us = self.min_us + total_range * degrees // self.angle
        self.write_us(us)
        
# 舵机小臂
mMin = Servo(Pin(15,Pin.OUT))
# 舵机大臂
mMax = Servo(Pin(13,Pin.OUT))

#控制在90度
mMax.write_angle(80) # 90度 0度相差-10度
mMin.write_angle(83) # 0度

# 相对变量
x = 9
y = 11
lmax = 9
lmin = 9
angleMaxBase = -10 # 大臂表示0度
angleMinBase = 83 # 小臂表示0度
highBase = 2 # 基座高度
# y坐标 1-17

def arm(x,y):
  try:
    y = y-highBase
    z = (x**2+y**2)**0.5
    print("z",z)
    v1 = (x**2+z**2-y**2)/(2*x*z)
    angle1 = degrees(acos(v1))
    print("1:",angle1)

    v2 = (lmax**2+z**2-lmin**2)/(2*lmax*z)
    angle2 = degrees(acos(v2))
    print("2:",angle2)
    
    v3 = (lmin**2+lmax**2-z**2)/(2*lmin*lmax)
    angle3 = degrees(acos(v3))
    print("3:",angle3)    

    #大臂角
    sensorMax = angle1 + angle2
    #小臂角
    sensorMin = 180 - sensorMax - angle3
    print("大臂:",sensorMax,"小臂:",sensorMin)

    runAngleMin = int(angleMinBase + sensorMin)
    runAngleMax = int(angleMaxBase + sensorMax)
    print("大臂执行:",runAngleMax,"小臂执行:",runAngleMin)
    mMin.write_angle(runAngleMin) # 0度
    mMax.write_angle(runAngleMax) # 90度 0度相差-10度    
  # except OSError as e:
  except:
    print("舵机异常",e)
#arm(right,180,0)
# arm(x,y)
# time.sleep(3)
# arm(3,15)
# time.sleep(2)
# for i in range(150,30,-1):
#     arm(3,i/10.0)
#     time.sleep(0.03)    
# for i in range(30,150):
#     arm(i/10.0,3)
#     time.sleep(0.03)

# 网络
def exec_pin_out(pin_num,value):
    p = Pin(pin_num,Pin.OUT)
    # p.on()
    # p.off()
    p.value(value)
    return True

def connect_wifi(essid,password):
    exec_pin_out(2,0)
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(essid,password)
    # if not wlan.isconnected():
    #     #print('connecting to network...')
    #     wlan.connect(essid,password)
    #     time.sleep(1)
    #     if not wlan.isconnected():
    #         connect_wifi(essid,password)
    exec_pin_out(2,1)
    print('network config:', wlan.ifconfig())
    return wlan.ifconfig()[0]
ip = connect_wifi("tianwanggaidihu","dabingjiayiqie")

import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.bind(('192.168.31.88', 80))
s.bind((ip, 80))
s.listen(5)
arm(9,11)

while True:
  try:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
    print('Content = %s' % request)
    apiReq = request.find('/?')
    if apiReq == 6:
        _list = request.split("/?")[1].split(" HTTP")[0].split("&")
        y = _list[0].split("=")[1]
        x = _list[1].split("=")[1]
        print("x:%s,y:%s"%(x,y))
        if x == "0":
          x = "1"
        if y == "0":
          y = "1"
        numx = 17*int(x)/100.0
        print("x:",numx,"%")
        numy = 17*int(y)/100.0
        print("y:",numy,"%")        
        arm(numx,numy)
        response = '{"status":"ok"}'
    else:
      response = """<html><head><meta charset="utf-8"><title>水平滑动条</title><style>*{margin:0;padding:0}.scroll{margin:100px;width:500px;height:5px;background:#ccc;position:relative}.bar{width:10px;height:20px;background:#369;position:absolute;top:-7px;left:0;cursor:pointer}.y{margin-bottom:-110px;margin-right:-100px}p{margin-left:100px}</style></head><body><div class="y">x水平方向</div><div class="scroll" id="scrollx"><div class="bar" id="barx"></div></div><p id="xP"></p><div class="y">y垂直方向</div><div class="scroll" id="scroll"><div class="bar" id="bar"></div></div><p id="yP"></p><script>var scroll=document.getElementById("scroll"),scrollx=document.getElementById("scrollx"),bar=document.getElementById("bar"),barx=document.getElementById("barx"),xP=document.getElementById("xP"),yP=document.getElementById("yP"),previous=0,x=0,y=0;bar.addEventListener("touchstart",function(e){console(e.clientX)}),bar.addEventListener("touchmove",function(e){console(e.clientX)}),bar.onmousedown=function(e){var e=e||window.event,t=e.clientX-this.offsetLeft;document.onmousemove=function(e){var e=e||window.event,n=e.clientX-t;n<0?n=0:n>scroll.offsetWidth-bar.offsetWidth&&(n=scroll.offsetWidth-bar.offsetWidth),bar.style.left=n+"px",y=parseInt(n/(scroll.offsetWidth-bar.offsetWidth)*100),yP.innerHTML="当前滑块的移动的百分比："+y+"%",window.getSelection?window.getSelection().removeAllRanges():document.selection.empty(),previous=throttle(previous,x,y,200)}},document.onmouseup=function(){document.onmousemove=null},barx.onmousedown=function(e){var e=e||window.event,t=e.clientX-this.offsetLeft;document.onmousemove=function(e){var e=e||window.event,n=e.clientX-t;n<0?n=0:n>scrollx.offsetWidth-bar.offsetWidth&&(n=scrollx.offsetWidth-bar.offsetWidth),barx.style.left=n+"px",x=parseInt(n/(scrollx.offsetWidth-bar.offsetWidth)*100),xP.innerHTML="当前滑块的移动的百分比："+x+"%",window.getSelection?window.getSelection().removeAllRanges():document.selection.empty(),previous=throttle(previous,x,y,200)}},document.onmouseup=function(){document.onmousemove=null};function throttle(e,t,n,s=100){let o=Date.now();return o-e>=s&&(console.log(e,o,o-e,s,o-e>=s),getApi(t,n),e=o),e}function getApi(e,t){console.log("x:",e,"y:",t);var n,s="/?y="+t+"&x="+e;console.log("url",s),n=fetch(s).then(function(e){return e.status===200?e.json():{}}),n=n.then(function(e){console.log(e)}).catch(function(e){console.log(e)})}</script></body></html>"""      
    print("前端请求:",apiReq)
    #response = """<h1>hi</h1><iframe src="http://192.168.31.223:9999/static/examples/toolbox-demo/"></iframe>"""

    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    time.sleep(0.01)
    conn.sendall(response)
    conn.close()
    time.sleep(0.01)  
  except:
      conn.close()
      print("错误:")
    
